package com.goods.business.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.converter.ConsumerConverter;
import com.goods.business.mapper.ConsumerMapper;
import com.goods.business.service.ConsumerService;
import com.goods.common.model.business.Consumer;
import com.goods.common.vo.business.ConsumerVO;
import com.goods.common.vo.system.PageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class ConsumerServiceImpl implements ConsumerService {

  @Autowired
  private ConsumerMapper consumerMapper;

  /**
   * 查询物资去向列表
   * @param pageNum
   * @param pageSize
   * @param consumerVO
   * @return
   */
  @Override
  public PageVO<ConsumerVO> findConsumerList(Integer pageNum, Integer pageSize, ConsumerVO consumerVO) {
    PageHelper.startPage(pageNum,pageSize);
    Example c = new Example(Consumer.class);
    Example.Criteria criteria = c.createCriteria();
    c.setOrderByClause("sort asc");
    if (consumerVO.getName()!=null&&!"".equals(consumerVO.getName())){
      criteria.andLike("name","%" + consumerVO.getName() + "%");
    }
    if (consumerVO.getAddress()!=null&&!"".equals(consumerVO.getAddress())){
      criteria.andLike("address","%" + consumerVO.getAddress() + "%");
    }
    if (consumerVO.getContact()!=null&&!"".equals(consumerVO.getContact())){
      criteria.andLike("contact","%" + consumerVO.getContact() + "%");
    }
    List<Consumer> consumers = consumerMapper.selectByExample(c);
    List<ConsumerVO> consumerVOS = ConsumerConverter.converterToVOList(consumers);
    PageInfo<Consumer> consumerPageInfo = new PageInfo<>();
    return new PageVO<>(consumerPageInfo.getTotal(),consumerVOS);
  }

  /**
   * 添加物资去向信息
   * @param consumerVO
   * @return
   */
  @Override
  public Consumer add(ConsumerVO consumerVO) {
    Consumer consumer = new Consumer();
    BeanUtils.copyProperties(consumerVO,consumer);
    consumer.setCreateTime(new Date());
    consumer.setModifiedTime(new Date());
    consumerMapper.insert(consumer);
    return consumer;
  }

  /**
   * 点击编辑显示编辑页面物资去向信息
   * @param id
   * @return
   */
  @Override
  public ConsumerVO edit(Long id) {
    Consumer consumer = consumerMapper.selectByPrimaryKey(id);
    return ConsumerConverter.converterToConsumerVO(consumer);
  }

  /**
   * 点击确定按钮提交修改物资去向信息
   * @param id
   * @param consumerVO
   */
  @Override
  public void update(Long id, ConsumerVO consumerVO) {
    Consumer consumer = new Consumer();
    BeanUtils.copyProperties(consumerVO,consumer);
    consumer.setModifiedTime(new Date());
    consumerMapper.updateByPrimaryKeySelective(consumer);
  }

  /**
   * 删除物资去向信息
   * @param id
   */
  @Override
  public void delete(Long id) {
    consumerMapper.deleteByPrimaryKey(id);
  }
}
